<?php

namespace app\store\controller;

use think\Controller;
use think\Db;
use think\Image;
use think\Request;
use think\Validate;
use think\Cache;
use think\Session;
class ApiCommon extends Controller
{
    protected $req; //用来处理客户端传递过来的参数
    protected $validater; //用来验证数据/参数
    protected $params; //过滤后符合要求的参数

	protected $rules = array();
	protected $nocheckArr = array();
    /**
     * [构造方法]
     * @return [type] [description]
     */
    protected function _initialize()
    {

        parent::_initialize();
        $this->req = Request::instance();
		$funstr =  $this->req->action();
		
		//exit('$funstr='.$funstr.'jsons='.json_encode($this->nocheckArr));
//		测试去掉
		if(!in_array($funstr, $this->nocheckArr)){
			 //1. 验证token
//      	$this->checkToken($this->req->param());
			//$this->checkLogin();
			//echo 'aaabbccddeeff'.json_encode($this->nocheckArr).'=funstr='.$funstr;
			$this->isCanUse();
		}      
		
    }
	
	function checkLogin(){
		
		$logintp = session('?logintp');
		if($logintp != 'xcx' && !session('?openid')){
			//exit('$urls='.$urls);
			//session('loginurl',$urls);
			//header("Location:".$urls);
			
			//$url='http://'.$_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]; 
			//echo dirname($url);
			$this->returnMsg(400, '重新授权');
		}
	}
	
	function isCanUse(){
		
		$pararr = $this->req->param();
		if (isset($pararr['storeid'])){
			$storeid = $pararr['storeid'];
		}
		else{
			$storeid = session('storeid');
		}
		
		if($storeid > 0){
			$storeres = Db::name('store')->where(['store_id'=>$storeid])->find();
			
			if(!$this->isCanUseFun($storeid)){
				$this->returnMsg(4001, '对不起,店铺有效期已过');				
			}
		}
	}
	
	function isCanUseFun($storeid){
		$storeres = Db::name('store')->where(['store_id'=>$storeid])->find();
			
		if(!empty($storeres)){			
			$useendtime = strtotime($storeres['useendtime']);
			$isshow = $storeres['isshow'];
			$curtime = time();
			if($curtime >$useendtime || $isshow !=1){
				return false;
			}			
		}
		return true;
	}

    //验证token方法 (防止篡改数据)
    /*
    $arr: 全部请求参数
    return : json
     */
    protected function checkToken($arr)
    {
        //检测客户端是否传递过来token数据
        if (!isset($arr['token']) || empty($arr['token'])) {
            $this->returnMsg(400, 'token不能为空');
        }
		
		if (!isset($arr['uid']) || empty($arr['uid'])) {
            $this->returnMsg(400, 'uid不能为空');
        }

        //这是客户端api传递过来的token
        $app_token = $arr['token'];
		//这是客户单传过来的uid
		$app_uid = $arr['uid'];
        //如果已经传递token数据，就删除token数据，生成服务端token与客户端的token做对比
        unset($arr['token']);
		
		//获取缓存的uid		
		$uidkey = Session::get($app_uid.'_key');
		
        $session_token = md5($app_uid.$uidkey);

        //如果传递过来的token不相等
        if ($app_token !== $session_token) {
            $this->returnMsg(400, 'token值不正确',['at'=>$session_token,'uk'=>$uidkey]);
        }
    }
	
	
	protected function getUid(){
		return $this->req->param()['uid'];
	}
	
    //检测客户端传递过来的其他参数（用户名，其他相关）
    /*
    param: $arr [除了time,token以外的其他参数]
    return:     [合格的参数数组]
     */
    protected function checkParams($arr)
    {
    	$rule = [
		    'token'  => 'require'
		];		
		$msg = [
		    'token.require' => 'token  fail'
		];
		
		$validate = new Validate($rule, $msg);
		$result   = $validate->check($data);
		
		if(!$result){
			return $this->returnMsg('400',$validate->getError());
		}
        return $arr;
    }


    //返回信息
    protected function returnMsg($code, $msg = '', $data = [])
    {
        $return_data['status'] = $code;
        $return_data['msg'] = $msg;
        $return_data['result'] = $data;
        echo json_encode($return_data);die;
    }

    /**
     * [上传文件到服务器]
     * @param  [object] $file [文件资源]
     * @param  [string] $type [图片类型]
     * @return [string]       [图片在服务器的路径]
     */
    public function uploadFiles($file, $type = '')
    {
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');

        if ($info) {
            //获取图片路径
            $path = '/uploads/' . $info->getSaveName();
            $path = preg_replace('/\\\\/', '/', $path);
            //裁剪图片
            if (!empty($type)) {
                $this->imageEdit($path, $type);
            }
        } else {
            $this->returnMsg(400, $file->getError());
        }

        return $path;
    }

    /**
     * [图片裁剪]
     * @param  [string] $path [原图片的绝对路径]
     * @param  [string] $type [图片的类型]
     * @return [null]
     */
    public function imageEdit($path, $type)
    {
        $image = Image::open(ROOT_PATH . 'public' . $path);
        switch ($type) {
            case 'head_img':
                $image->thumb(200, 200, Image::THUMB_CENTER)->save(ROOT_PATH . 'public' . $path);
                break;
            case 'other_img':
                break;
        }
    }
}
